<?php
namespace System\Controller;
use Common\Controller\CommonController;
use System\Model\AdminModel;
class PublicController extends CommonController{
	protected $data = '';
	
	//生成验证码
	public function verify(){
		$Verify = new \Think\Verify();
		ob_clean(); //清空擦掉输出缓冲区,解决服务器上不显示二维码的问题
		$Verify->entry(1);
    }
    

    /**
     * 管理员登录
     * Enter description here ...
     */
    public function login(){
        if (IS_POST){
            //检测验证码
            (!check_verify(I('verify'),1)) && $this->rtnResult(1,'验证码不正确');

            //用户是否存在
            $map['a.username'] = I('post.username');
            $map['a.status'] = 0;
            $map['_string'] = 'a.fk_role_id = r.pk_id';
            $field = 'a.pk_id,a.password,a.encrypt,a.fk_role_id,a.nickname,r.name AS role_name,r.menu_auth,r.access_auth';
            $info = M()->table('sys_admin a,sys_role r')->where($map)->field($field)->find();
            empty($info) && $this->rtnResult(1,'用户名不存在或密码错误[code:1]');

            //密码是否正确
            if (strengthen_md5(I('post.password'),$info['encrypt']) != $info['password']){
                $this->rtnResult(1,'用户名不存在或密码错误code:2');
            }

            //是否有可访问权限
            ($info['fk_role_id'] != 1 && !$info['menu_auth']) && $this->rtnResult(1,'您没有可访问的系统菜单，请联系超级管理员配置。');

            //缓存用户信息
            createAdminToken($info);

            //记录最近一次更新时间
            $loginData['lastloginip'] = get_client_ip();
            $loginData['lastlogintime'] = time();
            M('SysAdmin')->where('pk_id = %d',$info['pk_id'])->save($loginData);
            $this->rtnResult(0,'登录成功',U('Admin/Index/index'));
        }else {
            $this->display();
        }
    }

	/**
     * 取回密码
     * Enter description here ...
     */
    public function retrievePwd(){
    	if (IS_POST){
            //检测验证码
            (!check_verify(I('verify'),1)) && $this->rtnResult(1,'验证码不正确');

            $password = I('password');
            $repassword = I('repassword');
            $uniqid = I('uniqid');
            (!$uniqid || !$password || !$repassword) && $this->rtnResult(1,'无效的请求');

            $uniqid_info = json_decode(aes_decrypt($uniqid),true);
            !$uniqid_info && $this->rtnResult('无效的校验码');

            if(time() - $uniqid_info['timestamp'] > 30 * 60){
                $this->rtnResult('校验码已过期，请重新获取');
            }
            if($password != $repassword){
                $this->rtnResult('两次密码输入不一致');
            }
            $admin_model = M('admin');
            $info = $admin_model->where("username = '%s'",$uniqid_info['username'])->field('pk_id,encrypt,password')->find();
            !$info && $this->rtnResult(1,'无效的校验码');

            $new_password = strengthen_md5($password,$info['encrypt']);
            $result = $admin_model->where('pk_id = %d',$info['pk_id'])->setField('password',$new_password);
            !$result && $this->rtnResult(1,'密码修改失败');
            $this->rtnResult(0,'密码修改成功',U('login'));
    	}else {
    		$this->display();
    	}
    }

    /**
     * 申请取回密码（获取邮件）
     */
    public function applyRetrievePwd(){
        $username = I('username');
        $adminModel = new \System\Model\AdminModel();
        $info = $adminModel->where("username = '%s'",$username)->field('pk_id,email,nickname')->find();
        !$info && $this->rtnResult(1,'您未设置邮箱或账户名输入错误[code:1]');
        if ($info['email']){
            //存储唯一标识
            $data = array(
                'username'   =>  $username, //用户名
                'timestamp' =>  time(), //邮件发送时间
                'uniqid'  =>  uniqid('',true) //随机数，用于混淆
            );
            $unique = urlencode(aes_encrypt(json_encode($data)));
            $content = '尊敬的用户'.$info['nickname'].':<br/>&nbsp;&nbsp;请点击以下地址取回密码，有效期为30分钟';
            load('Common.mail');
            $result = think_send_mail($info['email'], $info['nickname'] ,'取回密码',$content.U('System/Public/retrievePwd').'/?uniqid='.$unique);
            if ($result !== true){
                $this->rtnResult(1,'发送失败');
            }else {
                $this->rtnResult(0,'邮件已发送到您的邮箱上，请注意查收！');
            }
        }else{
            $this->rtnResult(1,'您未设置邮箱或账户名输入错误[code:2]');
        }
    }
    

    /**
     * 退出登录
     * Enter description here ...
     */
    public function loginOut(){
        delAdminToken();
        $this->success('退出成功！', C('APP_URL').'/admin.php');
    }
    
    
	/**
     * 析构函数，数据不回宫时返回(non-PHPdoc)
     * @see Think.Controller::__destruct()
     */
    public function __destruct(){
    	if (IS_POST && !empty($this->data)){
    		$this->ajaxReturn($this->data);
    	}
    }
}
?>